<template>
  <t-card :bordered="false">
    <!-- 自定义搜索 -->
    <custom-search ref="customSearchRef" v-slot="{ params }"
      :default-params="{ sjsg: [],status:defaultStatus }" @submit="handleSeachTable">
      <t-col :span="3">
        <t-form-item label="客户名称" name="customerName">
          <t-input v-model:value="params.customerName" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="客户手机号" name="phone">
          <t-input v-model:value="params.phone" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="施工阶段" name="stage">
          <t-select v-model:value="params.stage" :options="dictionaryStore.get('engineering_stage')" clearable
            filterable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="工程状态" name="status">
          <t-select v-model:value="params.status" :options="dictionaryStore.get('engineering_status')" clearable
            filterable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="设计师" name="designerId">
          <t-cascader
            v-model:value="params.designerId"
            :options="designerTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
 
          />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="工程部经理" name="engineeringManagerId">
          <t-cascader
            v-model:value="params.engineeringManagerId"
            @change="(val,text) => getCurrentDeptId(val,text)"
            :options="engineeringManagerTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
          />
        </t-form-item>
       
      </t-col>
      <t-col :span="3">
        <t-form-item label="监理" name="supervisionId">
          <t-cascader
            v-if="!params.engineeringManagerId"
            v-model:value="params.supervisionId"
            :options="supervisionTree"
            :keys="{ value: 'id', label: 'name' }"
            placeholder=""
            filterable
            clearable
          />
          <t-select 
            v-else
            v-model:value="params.supervisionId" 
            :options="currentDeptUsers.supervisions"
            :keys="{ label: 'nickname', value: 'id' }" placeholder="" clearable filterable
            @clear="params.supervisionId = null" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="楼盘名称" name="propertyName">
          <t-select v-model:value="params.propertyName" clearable filterable placeholder="">
            <t-option v-for="_ in propertyInfoList" :key="_.id" :value="_.id" :label="_.name">
              {{ _.name }}
              <span style="color: var(--td-text-color-secondary)">{{ _.address }}</span>
            </t-option>
          </t-select>
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="详细地址" name="address">
          <t-input v-model:value="params.address" clearable placeholder="" />
        </t-form-item>
      </t-col>
      <t-col :span="3">
        <t-form-item label="实际竣工时间" name="sjsg">
          <t-date-range-picker
            allow-input v-model:value="params.sjsg" clearable enable-time-picker placeholder=" "
            style="width: 100%" 
            @change="
              (value) => {
                const [actualBeginTime, actualEndTime] = value;
                params.actualBeginTime = actualBeginTime;
                params.actualEndTime = actualEndTime;
              }
            "/>
        </t-form-item>
      </t-col>
    </custom-search>
    <!-- 自定义表格 -->
    <custom-table 
      ref="customTableRef" 
      row-key="id" 
      :columns="columns" 
      :api="engineeringListCRUD.page"
      column-controller-key="ProjectEngineeringList"
       :on-before-set-data="handleTableSetData"
    >
      <template #topContent>
        <div style="margin-bottom: var(--td-comp-margin-xxl)">
          <t-radio-group v-model="defaultCompany" theme="button" @change="handleCompanyChange">
            <t-radio-button :value="_.id" v-for="_ in companyList">{{ _.name }}</t-radio-button>
          </t-radio-group>
          <div style="margin-top: 6px;">
            <span v-if="hasData" style="margin-left: 10px;">
            <span v-for="stage in processedStages" :key="stage.value" class="stage-item">
              <span>{{ stage.label }}</span>
              <t-link theme="primary" v-if="stage.count > 0" @click="handleClick(stage.value, stage.ids)">
                {{ stage.count }}条；
              </t-link>
          
            </span>
          </span>
          <span v-if="hasData&&overdueStages.length>0">
            其中
            <span v-for="stage in overdueStages" :key="stage.value" class="stage-item">
            <span>{{ stage.label }}</span>
            <t-link theme="primary"  @click="handleClick(stage.value, stage.ids)">
              {{ stage.count  }}条；
            </t-link>
          </span>
          </span>
          </div>
        </div>
      </template>

      <template #customerName="{ row }">
        <span :class="{ 'red-text': isTimeExpired(row.actualEndTime) }">
        {{ row.customerName }}
        </span>
        <div>
          <span v-if="row.payNumber">{{ chineseTranser(row.payNumber) }}期款</span>

          <span v-text="dictionaryStore.analysis('pay_status', row.payStatus)"></span>
          <!-- {{ dictionaryStore.analysis('pay_status', row.payStatus) }} -->
        </div>
      </template>
      <template #stage="{ row }">
        {{ dictionaryStore.analysis('engineering_stage', row.stage) }}
      </template>
      <template #status="{ row }">
        {{ dictionaryStore.analysis('engineering_status', row.status) }}
      </template>
      <template #saleId="{ row }">
        {{ userStore.getUserNameById(row.saleId) }}
      </template>
      <template #designerId="{ row }">
        {{ userStore.getUserNameById(row.designerId) }}
      </template>
      <template #engineeringManagerId="{ row }">
        {{ userStore.getUserNameById(row.engineeringManagerId) }}
      </template>
      <template #productDesignerId="{ row }">
        {{ userStore.getUserNameById(row.productDesignerId) }}
      </template>
      <template #supervisionId="{ row }">
        {{ userStore.getUserNameById(row.supervisionId) }}
      </template>
      <template #chaiQiangTeamId="{ row }">
        {{teamUserList.find((item) => item.id === row.chaiQiangTeamId)?.name}}
      </template>
      <template #qiQiangTeamId="{ row }">
        {{teamUserList.find((item) => item.id === row.qiQiangTeamId)?.name}}
      </template>
      <template #shuiDianTeamId="{ row }">
        {{teamUserList.find((item) => item.id === row.shuiDianTeamId)?.name}}
      </template>
      <template #waGongTeamId="{ row }">
        {{teamUserList.find((item) => item.id === row.waGongTeamId)?.name}}
      </template>
      <template #muZuoTeamId="{ row }">
        {{teamUserList.find((item) => item.id === row.muZuoTeamId)?.name}}
      </template>
      <template #youQiTeamId="{ row }">
        {{teamUserList.find((item) => item.id === row.youQiTeamId)?.name}}
      </template>
      <template #propertyName="{ row }">
        {{propertyInfoList.find((item) => item.id === row.propertyName)?.name}}
        <span style="color: gray;">{{ row.address }}</span>
      </template>
      <template #contractBeginTime="{ row }">
        {{ row.contractBeginTime&&dayjs(row.contractBeginTime).format('YYYY-MM-DD') }}
      </template>
      <template #contractEndTime="{ row }">
        {{ row.contractEndTime&&dayjs(row.contractEndTime).format('YYYY-MM-DD') }}
      </template>
      <template #actualBeginTime="{ row }">
        {{ row.actualBeginTime?dayjs(row.actualBeginTime).format('YYYY-MM-DD'):'' }}
      </template>
      <template #actualEndTime="{ row }">
        {{ row.actualEndTime?dayjs(row.actualEndTime).format('YYYY-MM-DD'):'' }}
      </template>
      <template #operation="{ row }">
        <t-space break-line>
          <!-- 查看施工 -->
          <view-engineering :id="row.id" :operate-type="toDoTreeJumpParams.operateType" />
          <!-- <handle-set :id="row.orderId" @request-success="handleDialogRequestSuccess" /> -->
          
          <t-dropdown :options="filteredOptions" @click="(data) => clickHandler(data, row)" :min-column-width="120">
            <t-link theme="primary">更多...</t-link>
          </t-dropdown>

        </t-space>
      </template>
    </custom-table>
    <change-status :id="engineeringId" ref="changeStatus" @request-success="handleDialogRequestSuccess" />
    <transfer-engineering-manager :id="engineeringId" ref="transferEngineeringManager"
      @request-success="handleDialogRequestSuccess" />
    <transfer-supervision :id="engineeringId" ref="transferSupervision" @request-success="handleDialogRequestSuccess" />
    <update-order ref="updateOrder" @request-success="handleDialogRequestSuccess" />
    <engineering-message ref="engineeringMessageRef" @request-success="handleDialogRequestSuccess" />
    <engineering-dialog  ref="engineeringDialogRef" @confirm="handleEngieeringConfirm" />
  </t-card>
</template>

<script lang="ts">
export default {
  name: 'EngineeringList',
};
</script>

<script setup lang="ts">
import dayjs from 'dayjs';
import { Dialog, DialogPlugin, MessagePlugin, TableCol } from 'tdesign-vue-next';
import { computed, onMounted, onUpdated, Ref, ref, useTemplateRef } from 'vue';

import { engineeringListCRUD, createProductOrder, updateEngineeringTemplate } from '@/api/project/engineering';
import { getCompanyList, getSimpleDeptList } from '@/api/system/dept';
import { propertyManageCRUD } from '@/api/config/property';
import CustomDialog from '@/components/custom/dialog/index.vue';
import CustomSearch from '@/components/custom/search/index.vue';
import CustomTable from '@/components/custom/table/index.vue';
import Upload from '@/components/upload/index.vue';
import ViewEngineering from '@/pages/project/details/components/ViewEngineering.vue';
import ChangeStatus from '@/pages/project/engineering/components/ChangeStatus.vue';
import TransferEngineeringManager from './components/TransferEngineeringManager.vue';
import TransferSupervision from './components/TransferSupervision.vue';
import UpdateOrder from './components/UpdateOrder.vue';
import EngineeringDialog from '@/pages/finance/contract/components/EngineeringDialog.vue';
import { useDictionaryStore, useUserStore } from '@/store';
import hasPermission from '@/utils/hasPermission';
import disposableParams from '@/utils/disposableParams';
import listToTree from '@/utils/listToTree';
import { getUserListByRoleCode } from '@/api/system/user';
import HandleSet from './components/HandleSet.vue';
import EngineeringMessage from './components/EngineeringMessage.vue';
import { engineeringTeamCRUD } from '@/api/config/common-config';
// 字典仓库
const dictionaryStore = useDictionaryStore();
// 用户仓库
const userStore = useUserStore();
// 公司列表
const companyList = ref([]);
// 默认公司
const defaultCompany = ref()
// 处理获取公司列表
const handleGetCompanyList = () => {
  getCompanyList()
    .then((data) => {
      companyList.value = [{ id: null, name: '全部公司' }, ...data];
      defaultCompany.value = null
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetCompanyList();
// 精简部门列表
const simpleDeptList = ref([]);
// 精简部门树
const simpleDeptTree = ref([]);
// 处理获取精简部门
const handleGetSimpleDeptTree = () => {
  getSimpleDeptList().then((data) => {
    simpleDeptList.value = data;
    simpleDeptTree.value = listToTree(data);
  });
};
handleGetSimpleDeptTree();
// 设计师列表
const designerList = ref([]);
// 工程部经理
const engineeringManagerList = ref([]);
// 监理
const supervisionList = ref([]);

// 获取用户通过rolecode
const fetchUsersByRole = async (roleCode: string, targetList: Ref<any[], any[]>) => {
  try {
    const data = await getUserListByRoleCode({ roleCode });
    data.forEach((item:any) => {
      item.name = item.nickname
      item.parentId = item.deptId
    });
    targetList.value = data;
  } catch (error) {
    console.error(`Error fetching users with role ${roleCode}:`, error);
    targetList.value = []; // Reset on error
  }
};
// 施工班组
const teamUserList = ref([]);
// 获取施工班组
const getTeamUserList = () => {
  const params = {
    pageSize: -1,
  };
  engineeringTeamCRUD.page(params).then((data) => {
    teamUserList.value = data.list
  }).catch(({ message }) => {
    MessagePlugin.error(message);
  });
};
getTeamUserList()
// 初始化所有用户
const initializeUserLists = () => {
  fetchUsersByRole('designer', designerList);
  fetchUsersByRole('supervision', supervisionList);
  fetchUsersByRole('engineering_manager', engineeringManagerList);
};

// Call initialization
initializeUserLists();
// 3. 合并部门和用户数据，生成树形结构
const generateCombinedTree = (deptTree: any[], userList: any[], userType: string) => {
  // 创建用户按部门ID分组的映射
  const userMap = new Map<number, any[]>();
  userList.forEach(user => {
    if (!userMap.has(user.deptId)) {
      userMap.set(user.deptId, []);
    }
    userMap.get(user.deptId).push({
      ...user,
      isUser: true,
      userType: userType
    });
  });

  // 递归处理部门树
  const processTree = (nodes: any[]): any[] => {
    return nodes.map(node => {
      const newNode = { ...node };
      
      // 处理子部门
      if (newNode.children) {
        newNode.children = processTree(newNode.children);
      } else {
        newNode.children = [];
      }
      
      // 添加当前部门的用户
      if (userMap.has(newNode.id)) {
        newNode.children.push(...userMap.get(newNode.id));
      }
      
      // 保留有用户或有子部门的节点
      if (newNode.children.length > 0) {
        return newNode;
      }
      
      return null;
    }).filter(Boolean);
  };

  return processTree(deptTree);
};
// 4. 计算属性：生成各种组合树
const designerTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, designerList.value, 'designer');
});

const engineeringManagerTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, engineeringManagerList.value, 'engineering_manager');
});

const supervisionTree = computed(() => {
  return generateCombinedTree(simpleDeptTree.value, supervisionList.value, 'supervision');
});
const currentDeptId=ref()
const currentDeptUsers = computed(() => {
  if (!currentDeptId.value) return {
    supervisions: [],
  };
  
  return {
    supervisions: supervisionList.value.filter(user => user.deptId === currentDeptId.value),
  };
});
const getCurrentDeptId = (val:any,text:any) => {
  currentDeptId.value = text.node.data.deptId||''
  customSearchRef.value.params.supervisionId = null
  
}
// 公司切换
const handleCompanyChange = () => {
  handleInitTable();
};
// 楼盘信息列表
const propertyInfoList = ref([]);
// 处理获取楼盘信息列表
const handleGetPropertyInfoList = () => {
  const params = {
    pageSize: -1,
  };
  propertyManageCRUD
    .page(params)
    .then((data) => {
      propertyInfoList.value = data.list;
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
};
handleGetPropertyInfoList();
// 列表下拉
const options = [
  { content: '修改状态', value: 1, permission: 'system:engineering:update-status' },
  { content: '转派工程部经理', value: 2, permission: 'system:engineering:update-engineering-manager' },
  { content: '转派监理', value: 3, permission: 'system:engineering:update-supervision' },
  { content: '生成产品订单', value: 4, permission: 'system:product-order:create' },
  { content: '编辑订单', value: 5, permission: 'system:order:update' },
  { content: '更改施工模板', value: 6, permission: 'system:engineering-stage:update-engineering-stage-template' },
  { content: '新建工地情况', value: 7, permission: '' },
];
const clickHandler = (data: any, row: any) => {
  engineeringId.value = row.id
  orderId.value = row.orderId
  if (data.content === '修改状态') {
    changeStatusDialogRef.value.handleOpenChangeStatusDialog('update', { id: row.id, status: row.status });
  } else if (data.content === '转派工程部经理') {
    transferEngineeringManagerDialogRef.value.handleOpenDialog('update', row);
  } else if (data.content === '转派监理') {
    if (!row.engineeringManagerId) {
      MessagePlugin.error('请先选择转派工程部经理');
      return
    }
    transferSupervisionDialogRef.value.handleOpenDialog('update', row);
  } else if (data.content === '生成产品订单') {
    const confirmDia = DialogPlugin({
      // header: '确认生成产品订单',
      body: '确定要生成产品订单吗？',
      confirmBtn: '确定',
      cancelBtn: '取消',
      onConfirm: () => {
        createProductOrder({orderId: row.orderId, contractId: row.contractId}).then(res => {
          confirmDia.hide()
          MessagePlugin.success('生成订单成功');
        }).catch(({ message }) => {
          MessagePlugin.error(message);
        });
      },
      onClose: () => {
        // 用户点击“取消”或关闭弹窗时的操作
        confirmDia.hide()
      },
    });
  } else if (data.content === '编辑订单') {
    updateOrderDialogRef.value.handleOpenDialog('update', { id: row.orderId })
  } else if (data.content === '更改施工模板') {
    engineeringDialogRef.value.open()
  } else if (data.content === '新建工地情况') {
    engineeringMessageRef.value.handleOpenDialog('create', { imageUrl:[],...row})
  }

};
// 施工模板
const engineeringDialogRef = useTemplateRef('engineeringDialogRef');
const engineeringMessageRef = useTemplateRef('engineeringMessageRef');
// 处理模板确认选择
const handleEngieeringConfirm = (stageModelId: any) => {
  const params = {
    engineeringId:engineeringId.value,
    newModelId:stageModelId,
    orderId:orderId.value
  }
  updateEngineeringTemplate(params).then((data) => {
      // handleRefreshTable()
      MessagePlugin.success('更改施工模板成功');

    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
  
};
const engineeringId = ref()
const orderId = ref()
// 根据权限过滤选项
const filteredOptions = computed(() => {
  return options.filter(option => hasPermission(option.permission));
});
// 自定义搜索ref
const customSearchRef = useTemplateRef('customSearchRef');
// 自定义表格ref
const customTableRef = useTemplateRef('customTableRef');
// columns
const columns: TableCol[] = [
  { colKey: 'stage', title: '工程阶段', width: 80, fixed: 'left' },
  { colKey: 'customerName', title: '客户名称', width: 130, fixed: 'left' },
  { colKey: 'status', title: '工程状态',width: 80, fixed: 'left' },
  { colKey: 'propertyName', title: '楼盘地址', fixed: 'left', width: 180 },
  { colKey: 'phone', title: '手机号码', width: 110 },
  { colKey: 'saleId', title: '客服', width: 80 },
  { colKey: 'designerId', title: '设计师', width:80 },
  { colKey: 'productDesignerId', title: '产品设计师', width: 90 },
  { colKey: 'engineeringManagerId', title: '工程部经理', width: 90 },
  { colKey: 'supervisionId', title: '监理', width: 80 },
  { colKey: 'actualEndTime', title: '实际竣工时间', width: 120 },
  { colKey: 'chaiQiangTeamId', title: '拆墙', width: 80 },
  { colKey: 'qiQiangTeamId', title: '砌墙', width: 80 },
  { colKey: 'shuiDianTeamId', title: '水电', width: 80 },
  { colKey: 'waGongTeamId', title: '瓦工', width: 80 },
  { colKey: 'muZuoTeamId', title: '木工', width: 80 },
  { colKey: 'youQiTeamId', title: '油工', width: 80 },
  { colKey: 'houseArea', title: '房屋面积', width: 80 },
  { colKey: 'contractBeginTime', title: '合同开工时间', width: 120 },
  { colKey: 'contractEndTime', title: '合同竣工时间', width: 120 },
  { colKey: 'actualBeginTime', title: '实际开工时间', width: 120 },

  { colKey: 'contractPrice', title: '合同总价(元)', width: 120 },
  { colKey: 'operation', title: '操作', width: 120, fixed: 'right' },
];
 // 待办树跳转参数
 const toDoTreeJumpParams = disposableParams.get('to-do-tree-jump-params');
 const handleSeachTable=(params:any) =>{
  if(params=='reset') {
    customSearchRef.value.params.status = ''
  }
  disposableParams.set('to-do-tree-jump-params', {
    orderIds: '',
  });
  handleInitTable()
  
}
// 处理初始化表格
const handleInitTable = () => {
  if(customSearchRef.value.params.orderIds||toDoTreeJumpParams.orderIds) {
    // customSearchRef.value.params.stage = ''
    // customSearchRef.value.params.status = ''
  }
  const params = { orderIds: toDoTreeJumpParams.orderIds,...customSearchRef.value.params, companyId: defaultCompany.value, };
    if (!params.sjsg.length) {
    delete params.actualEndTime;
    delete params.actualBeginTime;
  }
  customTableRef.value.initTable(params);
  customSearchRef.value.params.orderIds =''
};
// 处理刷新表格
const handleRefreshTable = () => {
  customTableRef.value.refreshTable();
};
const defaultStatus = computed(() => {
  if (!toDoTreeJumpParams.orderIds) {
    return '2';
  }
  return '';
});
onMounted(() => {
  handleInitTable();
});
onUpdated(() => {
  handleRefreshTable();
})
// 修改状态对话框ref
const changeStatusDialogRef = useTemplateRef('changeStatus');
// 转派工程部经理对话框ref
const transferEngineeringManagerDialogRef = useTemplateRef('transferEngineeringManager');
// 转派监理对话框ref
const transferSupervisionDialogRef = useTemplateRef('transferSupervision');
// 编辑订单对话框ref
const updateOrderDialogRef = useTemplateRef('updateOrder');
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  if (result.mode === 'create') handleInitTable();
  if (result.mode === 'update') handleRefreshTable();
};
// 判断时间是否已过期（大于当前时间）
const isTimeExpired = (timeString:any) => {
  if(timeString) {
    return new Date(timeString) < new Date();
  }
};
const chineseTranser = (num: number) => {
  const chineseNumbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  return chineseNumbers[num] || num;
};
const tableTotal = ref<Record<string,any>>({})
// 处理表格设置数据
const handleTableSetData = (data: any) => {
  tableTotal.value = data.data
  return data
};
const hasData = computed(() => {
  return Object.keys(tableTotal.value).length > 0;
});
const processedStages = computed(() => {
  if(!hasData.value) return []
  return [
    {label:'待开工',value:'daikaigong'},
    {label:'施工中',value:'shigongzhong'},
    {label:'工程已竣工',value:'jungong'},
    {label:'工程已停工',value:'tinggong'},
    {label:'退单',value:'tuidan'},
  ].map(stage => {
        const ids = tableTotal.value[stage.value] ? tableTotal.value[stage.value].split(',') : [];
        
        
        return {
          ...stage,
          ids,
          count: ids.length,
        };
      }).filter(stage => stage.count > 0);
});
// 所有延期数据
const overdueStages = computed(() => {
  if(!hasData.value) return []
 return dictionaryStore.get('engineering_stage').map(stage => {
  const ids = tableTotal.value[stage.value] ? tableTotal.value[stage.value].split(',') : [];

    return {
      ...stage,
      ids,
      count: ids.length,
    };
  }).filter(stage => stage.count > 0);

});
// 点击条数
const handleClick= (stageValue:any,ids:any)=> {
  
  customSearchRef.value.params.stage = ''
  customSearchRef.value.params.status = ''
  customSearchRef.value.params.orderIds = ids.toString()
  handleInitTable()
  console.log(processedStages.value,'22');
  

}
</script>

<style lang="less" scoped>
:deep(.t-radio-group .t-radio-button) {
  border: none;
  border-radius: 18px !important;
  margin-left: 11px;
}

:deep(.t-radio-group .t-radio-button.t-is-checked) {
  background-color: #f2f3f5;
}
.red-text {
  color: red;
}
.stage-item {
  margin-right: 6px;
}
</style>
